﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using PloobsEngine.Physics;
using PloobsEngine.Draw;
using PloobsEngine.SceneControl;

namespace Etapa1.SteeringExperiments
{
    public class Cohesion : Steering
    {
        IWorld world;
        float rayOfAction = 500;
        List<IPhysicObject> collisionList = null;

        public List<IPhysicObject> CollisionList
        {
            get { return collisionList; }
            set { collisionList = value; rayOfAction = 0; }
        }

        public float RayOfAction
        {
            get { return rayOfAction; }
            set { rayOfAction = value; }
        }
        float weight = 10;
        Seek seek;

        public Cohesion(IWorld world)
            : base(BehaviorType.allignment)
        {
            this.world = world;
            seek = new Seek(Vector3.Zero);
        }

        public override Microsoft.Xna.Framework.Vector3 CalculateSteering(SteeringEntityInfo entity)
        {
            Vector3 steering = Vector3.Zero;
            List<IPhysicObject> list = null;
            if (rayOfAction <= 0)
            {
                list = collisionList;
            }
            else
            {
                list = world.PhysicWorld.GetPhysicsObjectsInRange(entity.Obj.PhysicObject, rayOfAction, (a,b) =>  true);
            }            
            int numAdded = 0;
            foreach (IPhysicObject obj in list)
            {
                if (obj != entity.Obj.PhysicObject && obj.PhysicObjectTypes != PhysicObjectTypes.TRIANGLEMESHOBJECT)
                {                    
                    steering += obj.Position;
                    numAdded++;
                }
            }

            if (numAdded > 0)
            {
                steering /= numAdded;
                seek.Target = steering;
                Drawing.DrawCircleOrDisk(5, Vector3.Up, steering, Color.Brown, 100, false,true);
                Drawing.DrawCircleOrDisk(rayOfAction, Vector3.Up, entity.Obj.Position, Color.Brown, 100, false,true);
                return seek.CalculateSteering(entity); ;
            }
            else
            {
                Drawing.DrawCircleOrDisk(rayOfAction, Vector3.Up, entity.Obj.Position, Color.Brown, 100, false, true);
                return Vector3.Zero;
            }
        }
    }
}
